import moment from 'moment';
import { Tooltip, message } from 'antd';
import MyIcon from '@/components/MyIcon';
import { ILoadMapTypeAll } from '@/common';
import { BZZ_CHECKSTATE } from '../../Acommon';
import { UploadFormCommon } from '../../Acomponents/UploadForm';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import { downloadTemplate, getCompanyID, getFileNameNotType, getPosIDs, getTenantID, getUserDepID, getUserID, splitFileUrl } from '@/utils';

/**`1000` 起草【需求编制】*/
export const XQBZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1000`;
/**`1009` 已确认*/
export const YQR_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1009`;
/**`1010` 已汇总*/
export const YHZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1010`;
/**`1008` 审核中*/
export const SHZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1008`;
/**`1006` 计划下达*/
export const JHXD_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1006`;
/**`1007` 已作废*/
export const XQZF_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1007`;
/**`1011` 已失效*/
export const YSX_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1011`;

/**`1004` 集中论证*/
export const JZLZ_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1004`; //【作废】
/**`1002` 科创部专责复核*/
export const KCBSH_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1002`; //【作废】
/**`1005` 主任办公会审议*/
export const ZRBGH_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1005`; //【作废】
/**`1003` 编制中*/
export const FGLDSH_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1003`; //【作废】
/**`1001` 部门审核*/
export const BMSH_STATE = () => `${getTenantID()}${ILoadMapTypeAll.NEED_STATE}1001`; //【作废】

/**
 * 工作流使用
 * */
/**业务Controller【controller】*/
export const purchaseNeedController = 'purchaseNeedController';
/**`1002`采购需求工单类型【orderType】*/
export const purchaseNeedOrderType = () => `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1009`;
/**`9903`流程相关&流程类别【category】*/
export const purchaseNeedCategory = () => `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1000`;
/**`2202`采购需求流程类别【businessCategory】【采购类别】*/
export const purchaseNeedBusinessCategory = () => `${getTenantID()}${ILoadMapTypeAll.NEED_BUSINESSTYPE}1000`;

/**表格斑马线设置使用*/
export const setTableRowClassName = (_: Record<string, any>, index: number) => (index % 2 == 0 ? 'double-row' : 'default-row');

/**添加计划处理数据*/
export const setPlanDataFunc = (resObj: Record<string, any>) => {
  let allPrepareNum: number = 0;
  let purchaseNeedMaterials: any[] = [];
  resObj?.purchaseNeedMaterials?.forEach((item: Record<string, any>) => {
    allPrepareNum += item?.expectNum;
    purchaseNeedMaterials?.push({ id: item?.materialID });
  });
  let reqParams = {
    ...resObj,
    // 标题替换
    planName: resObj?.needName,
    planInfo: resObj?.needInfo,
    state: 0, // 状态
    prepareNum: allPrepareNum, // 待采购数量
    createrID: getUserID(), // 创建人信息
    createPositionID: getPosIDs(),
    createDepartmentID: getUserDepID(),
    createCompanyID: getCompanyID(),
    purchaseNeedMaterials: purchaseNeedMaterials,
    mpurchaseNeeds: [{ id: resObj?.id }],
  };
  return reqParams;
};

/**
 * 处理省市县
 * @param resObj
 * @returns
 */
export const disposeArea = (resObj: Record<string, any>): any => {
  /***处理省市县**/
  if (resObj?.contaNode?.length) {
    let CodeArr = [...resObj?.contaNode];
    resObj.provinceCode = CodeArr?.[0];
    resObj.cityCode = CodeArr?.[1];
    resObj.countyCode = CodeArr?.[2];
  }
  return resObj;
};

/**判断预估单价是否为空的方法*/
export const isExpectPriceNull = (data: Record<string, any>) => {
  const bool = data?.list?.every((item: Record<string, any>) => {
    return item?.expectPrice > 0;
  });
  return bool;
};

/**根据0-1返回-是否*/
export const isShowPass = (val: number | string) => {
  val = Number(val);
  if (val) {
    return <span>是</span>;
  } else {
    return <span>否</span>;
  }
};

/** 专用--处理单位 */
export const getColorTextDoms = (text: any) => {
  if (text) {
    const [colorText, color] = text?.split('||');
    if (colorText?.length == 12) {
      return (
        <>
          <span>{'个'}</span>
        </>
      );
    }
    return (
      <>
        <span style={{ color: color }}>{colorText || '--'}</span>
      </>
    );
  } else {
    return <span>个</span>;
  }
};

/**文件上传判断*/
export const isShowUploadBtn = ({ record, needInfo, form, onEditTable, fileName, judgeName, nodesFlowListMemo }: Record<string, any>) => {
  /**
   * 判断上传按钮对应的switch是不是关闭状态，如果是则直接显示--
   * */
  if (record?.[judgeName] == '0') {
    return '/';
  } else {
    // 这里说明是switch选中
    /**
     * 判断一下状态是不是"待论证"
     * */
    if (needInfo?.state == JZLZ_STATE() && needInfo?.checkState == BZZ_CHECKSTATE() && nodesFlowListMemo) {
      return (
        <UploadFormCommon
          form={form}
          // requiredLabel="需求论证意见"
          fileFormName={fileName}
          spanCol={24}
          inRowProportion={24}
          spliceStr={8}
          name={'attachFile'}
          required={true}
          accept={'.doc|.docx|.pdf'}
          url={'/purchaseNeedController/uploadFile'}
          downloadUrl={'/purchaseNeedController/downloadFile'}
          fileFormDelName={'delLicenceUrl'}
          delFunc={(delFilePath) => {
            onEditTable({ value: null, key: fileName, type: 'UploadFormCommon', record });
          }}
          uploadSuccessCallback={(url) => {
            onEditTable({ value: url, key: fileName, type: 'UploadFormCommon', record });
          }}
          maxFile={1}
          defaultFiles={record && record?.id && record?.[fileName] != '' ? record?.[fileName] : null}
          hintTitle={'如上传多个，只保留第一个！'}
          fieldBusiPath={'purchase/need'}
          isShowUploadBtn={true}
        >
          上传
        </UploadFormCommon>
      );
    } else {
      /**
       * 如果不是"待论证"，则不能操作并且判断是否有值
       * */
      if (record && record?.id && record?.[fileName]) {
        return (
          <>
            {record?.[fileName] && splitFileUrl(record?.[fileName]).length > 0
              ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                  return (
                    <Tooltip title={e.attachName} key={new Date().getTime() * 859415685 + e?.attachName}>
                      <a
                        onClick={() => {
                          message.success('下载中，请稍后...');
                          downloadTemplate('/purchaseNeedController/downloadFile', e?.attachName, e?.attachUrl, () => {});
                        }}
                      >
                        <MyIcon type="icon-file-text-fill" />
                        &nbsp;
                        {getFileNameNotType(e.attachName, 8)}
                      </a>
                    </Tooltip>
                  );
                })
              : '/'}
          </>
        );
      } else {
        //没有值
        return '/';
      }
    }
  }
};

/**如果文件路径存在就渲染*/
export const renderNeedURL = (text: string | null) => {
  if (!text) return '/';
  return splitFileUrl(text)?.map((e, i) => {
    return (
      <Tooltip title={e.attachName} key={new Date().getTime() * 859415685 * new Date().getTime() + e?.attachName}>
        <a
          onClick={() => {
            message.success('下载中，请稍后...');
            downloadTemplate('/purchaseNeedController/downloadFile', e?.attachName, e?.attachUrl, () => {});
          }}
        >
          <MyIcon type="icon-file-text-fill" />
          &nbsp;
          {getFileNameNotType(e.attachName, 8)}
        </a>
      </Tooltip>
    );
  });
};

/**单选框-Tag类型*/
export const TagSelectRender = (label: string, name: string, required: boolean = false, value: number = 0) => {
  return (
    <TagSelect
      colSpan={12}
      formLabel={label}
      formRequired={required}
      formName={name}
      defalultKeys={isNaN(value) ? value : 0}
      radioList={[
        {
          value: 1,
          name: '是',
        },
        {
          value: 0,
          name: '否',
        },
      ]}
    />
  );
};

/**采购需求申请单-自动生成标题方法*/
export const getFormattedDateString = () => {
  // 获取当前日期的年份和月份
  const now = moment();
  const year = now.clone().add(1, 'months').format('YYYY');
  const month = now.clone().add(1, 'months').format('MM');
  // 构建格式化字符串
  const formattedString = `${year}年${month}月_采购计划`;
  return formattedString;
};

/**物料管理 -- <审核状态> -- 处理  返回div*/
export const signStateOfRendering = (state: number | null | undefined) => {
  if (typeof state !== 'number') return '--';
  if (state == 0)
    return (
      <div>
        <span style={{ color: '#4246d1' }}>待审核</span>
      </div>
    );
  else if (state == 1)
    return (
      <div>
        <span style={{ color: '#1e9392' }}>通过</span>
      </div>
    );
  else if (state == 2)
    return (
      <div>
        <span style={{ color: '#9d3df0' }}>驳回</span>
      </div>
    );
  else
    return (
      <div>
        <span style={{ color: '#5c6f91' }}>作废</span>
      </div>
    );
};

/**物料管理 -- <状态> -- 处理*/
export const stateOfRendering = (state: number | null | undefined, isShowIcon: boolean = true) => {
  if (typeof state !== 'number') return '--';
  if (state == 0) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#6812f2' }} />}
        <span style={{ color: '#6812f2' }}>起草</span>
      </div>
    );
  } else if (state == 1) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#2390fd' }} />}
        <span style={{ color: '#2390fd' }}>审核中</span>
      </div>
    );
  } else if (state == 2) {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#59d6a5' }} />}
        <span style={{ color: '#59d6a5' }}>有效</span>
      </div>
    );
  } else {
    return (
      <div>
        {isShowIcon && <MyIcon type="icon-dian" style={{ color: '#5c6f91' }} />}
        <span style={{ color: '#5c6f91' }}>无效</span>
      </div>
    );
  }
};

/**需求申请管理 -- <审核状态>*/
export const requirementApplicationFormat = (state: number | null | undefined) => {
  if (typeof state !== 'number') return '--';
  if (state == 1) {
    return <span style={{ color: '#0c880c' }}>通过</span>;
  } else {
    return <span style={{ color: '#e17ec7' }}>取消</span>;
  }
};

/** 当月的1号 - 当月的20号 为 true */
export const isMomentAddFun = () => {
  return true;
  const now = moment();
  const startOfMonth = now.clone().startOf('month').startOf('day'); // 本月第一天 00:00:00
  const endOfTwentieth = now.clone().startOf('month').add(19, 'days').endOf('day'); // 本月第20天 23:59:59
  return now.isBetween(startOfMonth, endOfTwentieth, null, '[]');
};

/** 当月21号 - 下月1号 为 true */
export const isMomentSubmitFun = () => {
  return true;
  const now = moment();
  const startOfTwentyFirst = now.clone().startOf('month').add(20, 'days').startOf('day'); // 本月第21天 00:00:00
  const endOfFirstOfNextMonth = now.clone().add(1, 'months').startOf('month').endOf('day'); // 下个月第一天 23:59:59
  return now.isBetween(startOfTwentyFirst, endOfFirstOfNextMonth, null, '[]');
};
